var server = window.location.host;   //getQueryString("server");
$("#server").val(server);
var full_ctx = "http://" + server;
// 页面加载后，需要做的
$().ready(function() {
			tt.vf.req.addId("tt_method", "templateName", "tt_request_url");
		});

var urlFormObj = document.getElementById("urlForm");
function getHtml(formId) {
	if (!tt.validateId('tt_request_url')) {
		return;
	}

	$.ajax({
				url : full_ctx + "/common/httpclient/getHtml.talent",
				data : $("#" + formId).serialize(),
				type : "POST",
				dataType : "jsonp",
				jsonp : "tio_http_jsonp",
				scriptCharset : 'UTF-8',
				cache : false,

				success : function(retObj) {
					// tt_complete();
					// var retObj = JSON.parse(_data.responseText);
					var result = tt_showResult(retObj);
					if (result) {
						var ss = retObj.data;
						var isJson = false;
						try {
							if (!talent_isSpecifiedType(ss, "String")) {
								ss = JSON.stringify(retObj.data);

							}
						} catch (e) {
							ss = retObj.data;
						}

						var container = document.getElementById("html_container");// = ss;
						document.getElementById("response_div").style.display = "";

						// 格式化显示
						var formatted_container = document.getElementById("html_container_json");
						formatted_container.innerHTML = "";
						try {
							var json = JSON.parse(ss);
							try{
								json.body = JSON.parse(json.body);
							} catch (e) {
							}
							
							
							var jsonStringInit = JSON.stringify(json);
							console.log(jsonStringInit);
							var jsonStringFormated = JsonUti.convertToString(json);
							container.innerHTML = jsonStringInit;
							
							showCode(jsonStringFormated, formatted_container);
							
						} catch (e) {
							console.log(e);
							formatted_container.innerHTML = ss;
							container.innerHTML = ss;

						}
					}
				}
			});
}

function showCode(str, co) {
	// var codeDiv = document.createElement("div");
	var codeAera = document.createElement("pre");

	// codeAera.name = "code";
	// codeAera.setAttribute('name', 'code'); // ff下须如此

	codeAera.className = "brush: js;";
	// codeAera.id = 'script_div';

	// co.appendChild(codeDiv);
	co.appendChild(codeAera);

	codeAera.innerHTML = str;
	//console.log(SyntaxHighlighter.highlight);
	SyntaxHighlighter.highlight();
}


function getCookie(formId) {
	if (!tt.validateId('tt_request_url')) {
		return;
	}
	$.ajax({
				url : full_ctx + "/common/httpclient/getCookie.talent",
				data : $("#" + formId).serialize(),
				type : "POST",
				dataType : "jsonp",
				jsonp : "tio_http_jsonp",
				scriptCharset : 'UTF-8',
				cache : false,

				success : function(retObj) {
					var result = tt_showResult(retObj);
					if (result) {
						var cookieEs = document.getElementsByName("cookies");
						for (var i = 0; i < cookieEs.length; i++) {
							cookieEs[i].value = "";
						}

						if (retObj.data) {
							for (var i = 0; i < retObj.data.length; i++) {
								cookieEs[i].value = retObj.data[i];
								cookieEs[i + 1].value = retObj.data[i];
							}
						}
					}
				}
			});
}

function loadTemplate(formId, templateAbsPath) {
	document.getElementById("templateName").value = templateAbsPath;
	if (!tt.validateId('templateName')) {
		return;
	}
	document.getElementById("response_div").style.display = "none";
	var _data = null;
	if (formId) {
		_data = $("#" + formId).serialize();
	} else {
		_data = {
			"templateAbsPath" : templateAbsPath
		};
	}
	$.ajax({
				url : full_ctx + "/common/httpclient/loadTemplate.talent",
				data : _data,
				type : "POST",
				dataType : "jsonp",
				jsonp : "tio_http_jsonp",
				scriptCharset : 'UTF-8',
				cache : false,

				success : function(retObj) {
					var result = tt_showResult(retObj);
					if (result) {
						fillWithJsonData(JSON.parse(retObj.data));
					}
				}
			});
}


function setDefautlvalueForRemark() {
	setValueForName("header_remark", ".");
	setValueForName("param_remark", ".");
	setValueForName("respremark_remark", ".");
}
function setValueForName(name, value) {
	var objs = document.getElementsByName(name);
	if (objs) {
		for (var i = 0; i < objs.length; i++) {
			if (!objs[i].value || !(objs[i].value.trim())) {
				objs[i].value = value;
			}
		}
	}
}


function saveTemplate(formId) {
	if (!tt.validateId('templateName')) {
		return;
	}
	setDefautlvalueForRemark();
	var html_container_value = document.getElementById("html_container").innerHTML;
	var _data1 = $("#" + formId).serialize();
	if (html_container_value) {
		var demovalue = encodeURIComponent(html_container_value);
//		if (demovalue.length > 8000){
//			var t1 = "";//demovalue.substr(0, 0);
//			var t2 = demovalue.substr(demovalue.length - 8000, demovalue.length);
//			demovalue = t1 + t2;
//		}
		
		_data1 = "resp_demo=" + demovalue + "&" + _data1;
	}
	
	if(confirm("确定保存?")){
		$.ajax({
			url : full_ctx + "/common/httpclient/saveTemplate.talent",
			data : _data1,
			type : "POST",
			dataType : "jsonp",
			jsonp : "tio_http_jsonp",
			scriptCharset : 'UTF-8',
			cache : false,

			success : function(retObj) {
				var result = tt_showResult(retObj, false);
				if (result) {
					//layer.msg('保存成功');
				} else {
					alert("保存失败");
				}
			}
		});
	}
}

function renameTemplate() {
	if(confirm("确定重命名?")){
		var _data = {};
		var templateName = document.getElementById("templateName").value;
		_data["newTemplateAbsPath"] = templateName;
	
		_data["oldTemplateAbsPath"] = oldtemplateid;
		$.ajax({
			url : full_ctx + "/common/httpclient/renameTemplate.talent",
			data : _data,
			type : "POST",
			dataType : "jsonp",
			jsonp : "tio_http_jsonp",
			scriptCharset : 'UTF-8',
			cache : false,
			success : function(retObj) {
				var result = tt_showResult(retObj);
				if (result) {
					layer.msg("重命名成功");
				}
				layer.close(layerindex);
			}
		});
	}
}

function deleteTemplate() {
	if(confirm("确定删除?")){
		var _data = {};
		var templateName = document.getElementById("templateName").value;
		_data["templateName"] = templateName;
		_data["isAbspath"] = true;
		$.ajax({
			url : full_ctx + "/common/httpclient/deleteTemplate.talent",
			data : _data,
			type : "POST",
			dataType : "jsonp",
			jsonp : "tio_http_jsonp",
			scriptCharset : 'UTF-8',
			cache : false,
			success : function(retObj) {
				var result = tt_showResult(retObj);
				if (result) {
					layer.msg("删除成功");
				}
				layer.close(layerindex);
			}
		});
	}
}

function clearResp(){
	var container = document.getElementById("html_container_json");
	container.innerHTML = "";
	document.getElementById("html_container").innerHTML = "";
}


var idIndex = 0;

/**
 * 
 * @param {}
 *            jsonData
 */
function fillWithJsonData(jsonData) {
	document.getElementById("tt_request_url").value = jsonData.url;
	document.getElementById("tt_remark").value = "";
	removeField('headerTable', 'headerTableBody', 'header', true);
	removeField('fieldTable', 'fieldTableBody', 'param', true);
	removeField('respremarkTable', 'respremarkTableBody', 'respremark', true);

	talent_c_setInputValueWithDataObj(jsonData, "", "", document
					.getElementById("urlForm"));

					
	document.getElementById("response_div").style.display = "none";
	// 格式化显示
	if (jsonData.resp_demo) {
		document.getElementById("response_div").style.display = "";
		var container = document.getElementById("html_container_json");
		container.innerHTML = "";
		document.getElementById("html_container").innerHTML = jsonData.resp_demo;
		try {
			var json = JSON.parse(jsonData.resp_demo);
			var jsonString = JsonUti.convertToString(json);
			showCode(jsonString, container);
		} catch (e) {
			console.log(e);
			container.innerHTML = jsonData.resp_demo;
		}
	}
	
	var requestHeaders = jsonData.requestHeaders;
	if (requestHeaders) {
		for (var i in requestHeaders) {
			var h = requestHeaders[i];
			if (talent_isSpecifiedType(h, "String")) {
				addField('headerTable', 'headerTableBody', 'header', i, h,
						null, full_ctx
								+ '/app-res/common/httpclient/httpHeaders.json');
			} else if (talent_isSpecifiedType(h, "Array")) {
				for (var k = 0; k < h.length; k++) {
					addField(
							'headerTable',
							'headerTableBody',
							'header',
							i,
							h[k].value,
							h[k].remark,
							full_ctx
									+ '/app-res/common/httpclient/httpHeaders.json');
				}
			} else {
				addField('headerTable', 'headerTableBody', 'header', i,
						h.value, h.remark, full_ctx
								+ '/app-res/common/httpclient/httpHeaders.json');
			}

		}
	}

	var requestParams = jsonData.requestParams;
	if (requestParams) {
		for (var i in requestParams) {
			var p = requestParams[i];
			var isArray = talent_isSpecifiedType(p, "Array");
			if (isArray) {
				for (var j = 0; j < p.length; j++) {
					var pv = p[j];
					if (talent_isSpecifiedType(pv, "String")) {
						addField('fieldTable', 'fieldTableBody', 'param', i, pv);
					} else if (talent_isSpecifiedType(pv, "Array")) {
						for (var k = 0; k < pv.length; k++) {
							addField('fieldTable', 'fieldTableBody', 'param',
									i, pv[k].value, pv[k].remark);
						}
					} else {
						addField('fieldTable', 'fieldTableBody', 'param', i,
								pv.value, pv.remark);
					}

				}
			} else {
				if (talent_isSpecifiedType(p, "String")) {
					addField('fieldTable', 'fieldTableBody', 'param', i, p);
				} else if (talent_isSpecifiedType(p, "Array")) {
					for (var k = 0; k < p.length; k++) {
						addField('fieldTable', 'fieldTableBody', 'param', i,
								p[k].value, p[k].remark);
					}
				} else {
					addField('fieldTable', 'fieldTableBody', 'param', i,
							p.value, p.remark);
				}

			}
		}
	}

	var respremark = jsonData.respremark;
	if (respremark) {
		for (var i in respremark) {
			var p = respremark[i];
			var isArray = talent_isSpecifiedType(p, "Array");
			if (isArray) {
				for (var j = 0; j < p.length; j++) {
					var pv = p[j];
					if (talent_isSpecifiedType(pv, "String")) {
						addField('respremarkTable', 'respremarkTableBody',
								'respremark', i, pv);
					} else if (talent_isSpecifiedType(pv, "Array")) {
						for (var k = 0; k < pv.length; k++) {
							addField('fieldTable', 'fieldTableBody', 'param',
									i, pv[k].value, pv[k].remark);
						}
					} else {
						addField('respremarkTable', 'respremarkTableBody',
								'respremark', i, pv.value, pv.remark);
					}

				}
			} else {
				if (talent_isSpecifiedType(p, "String")) {
					addField('respremarkTable', 'respremarkTableBody',
							'respremark', i, p);
				} else if (talent_isSpecifiedType(p, "Array")) {
					for (var k = 0; k < p.length; k++) {
						addField('fieldTable', 'fieldTableBody', 'param', i,
								p[k].value, p[k].remark);
					}
				} else {
					addField('respremarkTable', 'respremarkTableBody',
							'respremark', i, p.value, p.remark);
				}

			}
		}
	}

}

// addField('headerTable', 'headerTableBody', 'header', '', '',
// '${ctx}/app-res/common/httpclient/httpHeaders.json');
// addField('fieldTable', 'fieldTableBody', 'param');
function addField(tableId, tableBodyId, prefix, nameValue, valueValue,
		remarkValue, autoCompleteUrl) {

	if (autoCompleteUrl == 1) {
		autoCompleteUrl = full_ctx
				+ '/app-res/common/httpclient/httpHeaders.json';
	}
	autoCompleteUrl = null;

	var tableBody = document.getElementById(tableBodyId);
	var row = tableBody.insertRow(tableBody.rows.length);

	var cell = document.createElement("td");
	row.appendChild(cell);
	var inputEle3 = talent.Util.createInputElement("checkbox");
	cell.appendChild(inputEle3);

	cell = document.createElement("td");// theadRow.insertCell(theadRow.cells.length);
	row.appendChild(cell);
	var inputEle1 = talent.Util.createInputElement("text");
	cell.appendChild(inputEle1);
	inputEle1.setAttribute("name", prefix + "_name");
	inputEle1.style.width = "100px";
	inputEle1.value = nameValue ? nameValue : "";
	inputEle1.id = "name__ujh" + idIndex++;

	cell = document.createElement("td");// theadRow.insertCell(theadRow.cells.length);
	row.appendChild(cell);
	var inputEle2 = talent.Util.createInputElement("text");
	cell.appendChild(inputEle2);
	inputEle2.setAttribute("name", prefix + "_value");
	inputEle2.style.width = "400px";
	inputEle2.value = valueValue ? valueValue : "";
	inputEle2.id = "value__ujh" + idIndex++;

	cell = document.createElement("td");// theadRow.insertCell(theadRow.cells.length);
	row.appendChild(cell);
	var inputEle3 = talent.Util.createInputElement("text");
	cell.appendChild(inputEle3);
	inputEle3.setAttribute("name", prefix + "_remark");
	inputEle3.style.width = "800px";
	inputEle3.value = remarkValue ? remarkValue : "";
	inputEle3.id = "remark__ujh" + idIndex++;

	// /
	if (autoCompleteUrl) {
		var _fields = [{
					name : 'name',
					label : 'header'
				}, {
					name : 'remark',
					label : 'remark'
				}];
		var mapping = {};
		mapping[inputEle1.id] = "name";
		mapping[inputEle2.id] = "remark";

		var autocompleteConfig = {
			url : autoCompleteUrl,
			containerid : "autocompleteContainer1",
			inputObj : inputEle1,
			// events:["mouseover"],
			contextpath : full_ctx,
			skipValidate : true,
			ajaxConfig : {
				useCache : true
			},
			fields : _fields,
			isPagination : false,
			// formid: "addForm",
			showHeader : true, // 是否显示头
			countofstartquery : 0, // 必须要输入多少个字符才开始查询
			title : "", // 如果有值将会代替框架默认的title
			styles : {
				width : "800px"
			},
			gridConfig : {
				pageSize : 20,
				colorStyle : "red"
			},
			"mapping" : mapping
			// 用于
		};
		tt_autoeompleteSetup(autocompleteConfig);
		// inputEle1.fireEvent('');
	}

}

// removeField('headerTable', 'headerTableBody', 'header');
// removeField('fieldTable', 'fieldTableBody', 'param');
function removeField(tableId, tableBodyId, prefix, deleteAll) {
	var table = document.getElementById(tableBodyId);

	var rowCount = table.rows.length;
	for (var i = 0; i < rowCount; i++) {
		var row = table.rows[i];

		if (row.cells[0]) {
			var chkbox = row.cells[0].childNodes[0];
			if (deleteAll || (null != chkbox && true == chkbox.checked)) {
				table.deleteRow(i);
				rowCount--;
				i--;
			}
		}
	}
}

var OperHandler = function(config) {
	/**
	 * 删除数据
	 */
	this.del = function() {
		deleteTemplate('urlForm', config);
	};

};

function operRender(conf) {

}

var operField = {
	name : "oper",
	label : "操作",
	dataCellRenderConfig : {
		clazz : function(conf) {
			var operHandler = new OperHandler(conf);
			var delLink = tt_createGridDelBtn(conf.cell);

			talent.Util.addEventHandler(delLink, "click", operHandler.del);
		}
	}
};

function templateNameAutoeompleteSetup() {
	var inputEle = document.getElementById("templateName");
	var _fields = [{
				name : 'name',
				label : '模板名字',
				dataCellStyle : {
					textAlign : "left",
					paddingLeft : "5px"
				}
			}, {
				name : 'date',
				label : '创建日期'
			}, operField];
	var mapping = {};
	mapping["templateName"] = "name";

	var autocompleteConfig1 = {
		url : full_ctx + "/common/httpclient/getTemplateList.talent",
		containerid : "autocompleteContainer",
		inputObj : inputEle,
		contextpath : full_ctx,
		skipValidate : true,
		events : ["click"],
		formid : "urlForm",
		callback : function(record) {
			loadTemplate('urlForm');
		},
		ajaxConfig : {
			useCache : true
		},
		fields : _fields,
		isPagination : true,
		gridConfig : {
			pageSize : 20,
			colorStyle : "red"
		},
		// formid: "addForm",
		showHeader : false, // 是否显示头
		countofstartquery : 0, // 必须要输入多少个字符才开始查询
		title : "", // 如果有值将会代替框架默认的title
		styles : {
			width : "800px"
		},
		"mapping" : mapping
		// 用于
	};
	tt_autoeompleteSetup(autocompleteConfig1);
}
// templateNameAutoeompleteSetup();

var JsonUti = {
	// 定义换行符
	n : "\n",
	// 定义制表符
	t : "\t",
	// 转换String
	convertToString : function(obj) {
		return JsonUti.__writeObj(obj, 1);
	},
	// 写对象
	__writeObj : function(obj // 对象
			, level // 层次（基数为1）
			, isInArray) { // 此对象是否在一个集合内
		// 如果为空，直接输出null
		if (obj == null) {
			return "null";
		}
		// 为普通类型，直接输出值
		if (obj.constructor == Number || obj.constructor == Date
				|| obj.constructor == String || obj.constructor == Boolean) {
			var v = obj.toString();
			var tab = isInArray
					? JsonUti.__repeatStr(JsonUti.t, level - 1)
					: "";
			if (obj.constructor == String || obj.constructor == Date) {
				// 时间格式化只是单纯输出字符串，而不是Date对象
				return tab + ("\"" + v + "\"");
			} else if (obj.constructor == Boolean) {
				return tab + v.toLowerCase();
			} else {
				return tab + (v);
			}
		}
		// 写Json对象，缓存字符串
		var currentObjStrings = [];
		// 遍历属性
		for (var name in obj) {
			var temp = [];
			// 格式化Tab
			var paddingTab = JsonUti.__repeatStr(JsonUti.t, level);
			temp.push(paddingTab);
			// 写出属性名
			temp.push("\"" + name + "\" : ");
			var val = obj[name];
			if (val == null) {
				temp.push("null");
			} else {
				var c = val.constructor;
				if (c == Array) { // 如果为集合，循环内部对象
					temp.push(JsonUti.n + paddingTab + "[" + JsonUti.n);
					var levelUp = level + 2; // 层级+2
					var tempArrValue = []; // 集合元素相关字符串缓存片段
					for (var i = 0; i < val.length; i++) {
						// 递归写对象
						tempArrValue.push(JsonUti.__writeObj(val[i], levelUp,
								true));
					}
					temp.push(tempArrValue.join("," + JsonUti.n));
					temp.push(JsonUti.n + paddingTab + "]");
				} else if (c == Function) {
					temp.push("[Function]");
				} else {
					// 递归写对象
					temp.push(JsonUti.__writeObj(val, level + 1));
				}
			}
			// 加入当前对象“属性”字符串
			currentObjStrings.push(temp.join(""));
		}
		return (level > 1 && !isInArray ? JsonUti.n : "") // 如果Json对象是内部，就要换行格式化
				+ JsonUti.__repeatStr(JsonUti.t, level - 1) + "{" + JsonUti.n // 加层次Tab格式化
				+ currentObjStrings.join("," + JsonUti.n) // 串联所有属性值
				+ JsonUti.n + JsonUti.__repeatStr(JsonUti.t, level - 1) + "}"; // 封闭对象
	},
	__isArray : function(obj) {
		if (obj) {
			return obj.constructor == Array;
		}
		return false;
	},
	__repeatStr : function(str, times) {
		var newStr = [];
		if (times > 0) {
			for (var i = 0; i < times; i++) {
				newStr.push(str);
			}
		}
		return newStr.join("");
	}
};



function init() {
	

}
var oldtemplateid = null;
$(function() {
	init();	
	
	var loadid = getQueryString("id");
	oldtemplateid = loadid;
	//console.log(loadid);
	loadTemplate(null, loadid);
});
